package com.ruis.kotboot.api.kisso

import com.baomidou.kisso.SSOHelper
import com.baomidou.kisso.security.token.SSOToken
import com.ruis.kotboot.api.service.RuisCacheService
import com.ruis.kotboot.common.core.RuisException
import com.ruis.kotboot.common.util.HttpUtil
import com.ruis.kotboot.common.util.SpringContextHolder
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.cache.CacheManager

/**
 * Created by mgr on 2018/3/8.
 */

object KissoUtil{
    private val logger=LoggerFactory.getLogger(javaClass)
    private val ruisCacheService by lazy { SpringContextHolder.getBean(RuisCacheService::class.java) }
    private val cacheManager by lazy { SpringContextHolder.getBean(CacheManager::class.java) }

    fun getToken():SSOToken?{
        try {
            return SSOHelper.attrToken(HttpUtil.getRequest())?:SSOHelper.getSSOToken(HttpUtil.getRequest())
        }catch (e:Exception){}
        return null
    }
    fun isPermitted(permission: String): Boolean{
        return isPermitted(getToken(), permission)
    }
    fun isPermitted(token: SSOToken?, permission: String): Boolean{
        try {
            if(token==null)return false
            if(token.data!="admin")return false
            if(!StringUtils.isNumeric(token.id))return false
            if (StringUtils.isBlank(permission)) return false
//            return ruisCacheService.findUserById(token.id.toLong())?.types?.equals(permission)?:false
//            return ruisCacheService.findPermissionsByUserId(token.id.toLong())?.contains(permission)?:false
        }catch (e: RuisException){
            SSOHelper.clearLogin(HttpUtil.getRequest(),HttpUtil.getResponse())
        }catch (e:Exception){
            logger.error("kisso",e)
        }
        return false
    }



    /*fun getCacheUserById(id:Long?): SysUser?{
        if(id==null||id<0)return null
        return ruisCacheService.findUserById(id)
    }
    fun getCurrUser():SysUser?{
        return getCacheUserById(getToken()?.id?.toLong())
    }*/
}